//
//  AuthorViewController.swift
//  微博
//
//  Created by 段瑞金 on 16/5/15.
//  Copyright © 2016年 段瑞金. All rights reserved.
//

import UIKit
import SVProgressHUD
class AuthorViewController: UIViewController {
    //MARK:-懒加载
    private lazy var webView = UIWebView()


    override func loadView() {
        view = webView
        webView.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(AuthorViewController.closeBtnClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(AuthorViewController.autoFillAccount))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let str = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_Redirect_uri)"
        let url = NSURL(string: str)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
    }
    
    
    //关闭按钮
    @objc private func closeBtnClick ()-> () {
        dismissViewControllerAnimated(true, completion: nil)
 
        SVProgressHUD.dismiss()
    }
    @objc private func autoFillAccount () ->(){
        // 1.编写JS语句
        let jsStr = "document.getElementById('userId').value='1606020376@qq.com';" + "document.getElementById('passwd').value='haomage';"
        // 2.执行JS语句
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
    }

}

//MARK:-网络请求界面代理

extension AuthorViewController : UIWebViewDelegate {
    
    //每次有网络请求的时候都会调用
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
//        RJLOG(request.URL?.absoluteString)
        /*
         登录界面; https://api.weibo.com/oauth2/authorize?client_id=703655066&redirect_uri=http://www.520it.com
         
         授权界面: https://api.weibo.com/oauth2/authorize
         
         取消授权: http://www.520it.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
         
         授权成功: http://www.520it.com/?code=d8d35dc3b3145d42a4c6933764ae8982
         */

        // 1.检查是否是授权回调页, 如果是授权回调页, 那么不用显示
        // 1.1取出当前请求的URL
        guard let urlStr = request.URL?.absoluteString else {
            closeBtnClick()
            return false
        }
        
        // 1.2判断是否是授权回调页
        if !urlStr.hasPrefix(WB_Redirect_uri) {
            return true
        }
        
        // 2.判断是否是同意授权
        if !urlStr.containsString("error_uri=") {
            
            // 2.1获取code=所在的位置
            guard let range = urlStr.rangeOfString("code=") else {
                closeBtnClick()
                return false
            }
            // 2.2截取字符串
            let code = urlStr.substringFromIndex(range.endIndex)
//            RJLOG(code)
            loadAccessToken(code)
        }
        
        // 3.关闭授权界面
        closeBtnClick()
        return false
        
    }
    
    //开始网络请求的时候会调用
 func webViewDidStartLoad(webView: UIWebView)
   {
    
    
    /*
     MBProgressHUD
     MRC/ARC
     使用起来相对比较复杂
     没有提供任何素材
     
     SVProgressHUD
     ARC
     使用起来相对比较简单
     提供了一些简单的素材
     */

    

    SVProgressHUD.showWithStatus("正在加载...")
    }
    //加载完成之后会调用
 func webViewDidFinishLoad(webView: UIWebView)
 {
    SVProgressHUD.dismiss()
    }
    //加载错误的时候会调用
// func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
// {
//
//    SVProgressHUD.showErrorWithStatus("加载失败")
//    
//    }
    
    /**
     利用RequestToken换取AccessToken
     
     - parameter code: RequestToken
     */
    private func loadAccessToken(code: String) {
        
        // 1.准备路径
        let path = "oauth2/access_token"
        // 2.准备参数
        let parameters = ["client_id": WB_App_Key, "client_secret": WB_App_Secret, "grant_type": "authorization_code", "code": code, "redirect_uri": WB_Redirect_uri]
        
        // 3.发送请求
        
        NetWorkingTools.shareInstance.POST(path, parameters: parameters, success: { (task: NSURLSessionDataTask, objc: AnyObject?) -> Void in

            let accountItem = UserAccountItem(dict: objc as! [String : AnyObject])
            RJLOG(accountItem)
            accountItem.saveUserAccountItem()
        }) { (task :NSURLSessionDataTask?, error: NSError) -> Void in
            RJLOG(error)
        }
    }

    
}



